<template>
    <div class="courseEvaluate" @click="handleOutsideClick">
        <!-- 评论输入区域 -->
        <div class="comment-input-area">
            <div class="user-avatar">
                <img :src="currentUser?.avatarPath ? (baseUrl + currentUser?.avatarPath ) : defaultAvatar()" alt="">
            </div>
            <div class="comment-input-wrapper">
                <span class="username">{{ currentUser?.nickName }}</span>
                <EditorComponent class="editor" v-model="commentContent" ref="editorComponent" :noToolShadow="true" placeholder="写下你的评论..."
                 :toolbarConfig="['insertLink', 'insertImage', 'insertVideo', 'emotion']" />
                <div class="comment-tools">
                    <div class="right-tools">
                        <span class="word-count">{{ commentContent.length }}/200</span>
                        <ScoreComponent v-model="commentScore" :editor="true"></ScoreComponent>
                        <button class="send-btn" :disabled="!commentContent.trim()" @click="submitComment">
                            <span class="iconfont icon-likesprogramfasong"></span>发布</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
            <div v-for="comment in commentList" :key="comment.commentId" class="comment-item">
                <div class="user">
                    <div class="user-avatar">
                        <img :src="comment?.userInfo?.avatarPath ? (baseUrl + comment?.userInfo?.avatarPath ) : defaultAvatar()" alt="">
                    </div>
                    <div class="comment-content">
                        <div class="user-info">
                            <span class="username">{{ comment?.userInfo?.nickName }}</span>
                            <span class="time">{{ comment.createDate }}</span>
                            <span v-if="currentUser && comment.userId === currentUser.userId" class="delete-btn"
                                @click.stop="deleteComment(comment.commentId)">
                                删除
                            </span>
                            <ScoreComponent v-model="comment.score" :starSize="20"></ScoreComponent>
                        </div>
                        <div class="text-content" v-html="comment.content"></div>
                        <div class="comment-actions">
                            <div class="action-item" @click.stop="likeComment(comment.commentId)">
                                <span class="iconfont icon-likesprogramdianzan"></span>
                                <span>{{ 0 }}</span>
                            </div>
                            <div class="action-item" @click.stop="showReplyInput(comment.commentId)">
                                <span class="iconfont icon-likesprogramduihuakuang"></span>
                                <span>回复</span>
                            </div>
                            <!-- <div class="action-item">
                                <span class="iconfont icon-likesprogramjubao"></span>
                                <span>举报</span>
                            </div> -->
                        </div>

                        <!-- 回复列表 -->
                        <div class="reply-list" v-if="comment.children && comment.children.length > 0">
                            <div v-for="reply in comment.children" :key="reply.commentId" class="reply-item">
                                <div class="user-avatar">
                                    <img :src="reply?.userInfo?.avatarPath ? (baseUrl + reply?.userInfo?.avatarPath ) : defaultAvatar()" alt="">
                                </div>
                                <div class="reply-content">
                                    <div class="user-info">
                                        <span class="username">{{ reply?.userInfo?.nickName }}</span>
                                        <span class="time">{{ reply.createDate }}</span>
                                        <span v-if="currentUser && reply.userId === currentUser.userId"
                                            class="delete-btn"
                                            @click.stop="deleteReply(comment.commentId, reply.commentId)">
                                            删除
                                        </span>
                                    </div>
                                    <div class="text-content" v-html="reply.content"></div>
                                    <div class="comment-actions">
                                        <div class="action-item" @click.stop="likeComment(reply.commentId)">
                                            <span class="iconfont icon-likesprogramdianzan"></span>
                                            <span>{{ reply.score }}</span>
                                        </div>
                                        <div class="action-item"
                                            @click.stop="showReplyToReply(comment.commentId, reply)">
                                            <span class="iconfont icon-likesprogramduihuakuang"></span>
                                            <span>回复</span>
                                        </div>
                                        <!-- <div class="action-item">
                                            <span class="iconfont icon-likesprogramjubao"></span>
                                            <span>举报</span>
                                        </div> -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 回复输入框 -->
                        <div class="reply-input" v-if="activeReplyId === comment.commentId && !replyToReply"
                            @click.stop>
                            <div class="user-avatar">
                                <img :src="currentUser?.avatarPath ? (baseUrl + currentUser?.avatarPath ) : defaultAvatar()" alt="">
                            </div>
                            <div class="input-wrapper">
                                <EditorComponent class="editor" v-model="replyContent" ref="editorComponent" :noToolShadow="true" placeholder="写下你的回复..."
                                 :toolbarConfig="['insertLink', 'insertImage', 'insertVideo', 'emotion']" />
                                <div class="input-footer">
                                    <span class="count">{{ replyContent.length }}/200</span>
                                    <button class="submit-btn" :disabled="!replyContent.trim()"
                                        @click.stop="submitReply(comment.commentId)">
                                        <span class="iconfont icon-likesprogramfasong"></span>发布
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 回复的回复输入框 -->
                        <div class="reply-input" v-if="activeReplyId === comment.commentId && replyToReply" @click.stop>
                            <div class="user-avatar">
                                <img :src="currentUser?.avatarPath ? (baseUrl + currentUser?.avatarPath ) : defaultAvatar()" alt="">
                            </div>
                            <div class="input-wrapper">
                                <EditorComponent class="editor" v-model="replyContent" ref="editorComponent" :noToolShadow="true" placeholder="写下你的回复..."
                                 :toolbarConfig="['insertLink', 'insertImage', 'insertVideo', 'emotion']" />
                                <div class="input-footer">
                                    <span class="count">{{ replyContent.length }}/200</span>
                                    <button class="submit-btn" :disabled="!replyContent.trim()"
                                        @click.stop="submitReplyToReply(comment.commentId)">
                                        <span class="iconfont icon-likesprogramfasong"></span>发布
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 删除确认对话框 -->
        <MessageDialog ref="deleteDialog">
            <template #title>
                <span>删除评论</span>
            </template>
            <template #content>
                <div class="delete-confirm-content">
                    <span class="error-message">请确认是否删除该评论！</span>
                </div>
            </template>
            <template #footer>
                <div class="dialog-footer">
                    <button class="cancel-btn" @click="cancelDelete">取消</button>
                    <div class="divider"></div>
                    <button class="confirm-btn" @click="confirmDelete">确认</button>
                </div>
            </template>
        </MessageDialog>
    </div>
</template>

<script lang="ts">
import { ref, watch, onMounted } from 'vue';
import MessageDialog from '@/components/MessageDialog.vue';
import { useRoute } from 'vue-router';
import { courseApi } from '@/api/course/Course';
import { userApi } from '@/api/Users';
import { userAvatar as defaultAvatar } from '@/types/Base64Image';
import { baseUrl } from '@/util/request';
import { CourseComment } from '@/types/Course';
import ScoreComponent from '@/components/ScoreComponent.vue';
import EditorComponent from '@/components/EditorComponent.vue';
// import { ElMessage } from 'element-plus';

export default {
  name: 'courseEvaluate'
};
</script>

<script setup lang="ts">

    const route = useRoute();
    const courseId = ref(0);

    const currentUser = ref(null);
    const commentList = ref<CourseComment[]>([]);

    const commentContent = ref('');
    const commentScore = ref(5);
    const showEmojiPanel = ref(false);
    const activeReplyId = ref<number | null>(null);
    const replyContent = ref('');

    const deleteDialog = ref();
    let currentDeleteId: number | null = null;
    let isReply = false;

    // 使用CourseComment类型
    const replyToReply = ref<CourseComment | null>(null);


    /**
     * 在组件挂载时加载用户数据
     */
    onMounted(async () => {
        currentUser.value = await userApi.getLoginUserData(true);
    });

    /**
     * 点击外部关闭回复框
     */
    const handleOutsideClick = () => {
        if (activeReplyId.value !== null) {
            activeReplyId.value = null;
            replyContent.value = '';
        }
    };

    /**
     * 提交评论
     * 创建新的评论并发送到服务器
     */
    const submitComment = async () => {
        if (!commentContent.value.trim() || !currentUser.value) return;

        try {
            // 构建评论对象
            const commentData: Partial<CourseComment> = {
                courseId: courseId.value,
                userId: currentUser.value.userId,
                parentId: 0,  // 顶级评论
                content: commentContent.value,
                score: commentScore.value      // 初始点赞数为0
            };

            // TODO:调用API提交评论
            await courseApi.comment.addComment(commentData as CourseComment);
            console.log('评论提交成功');

            // 提交成功后重新获取评论列表
            await fetchComments(courseId.value);

            // 清空输入框
            commentContent.value = '';
            showEmojiPanel.value = false;
            commentScore.value = 5;
        } catch (error) {
            console.error('提交评论失败:', error);
        }
    };

    /**
     * 显示回复输入框
     * @param commentId 要回复的评论ID
     */
    const showReplyInput = (commentId: number) => {
        // 如果当前已经显示此评论的回复框，则关闭它，否则打开
        activeReplyId.value = activeReplyId.value === commentId ? null : commentId;
        replyToReply.value = null;
        replyContent.value = '';
    };

    /**
     * 提交回复
     * @param commentId 要回复的评论ID
     */
    const submitReply = async (commentId: number) => {
        if (!replyContent.value.trim() || !currentUser.value) return;

        try {
            // 构建回复对象
            const replyData: Partial<CourseComment> = {
                courseId: courseId.value,
                userId: currentUser.value.userId,
                parentId: commentId,  // 父评论ID
                content: replyContent.value,
                score: 0              // 初始点赞数为0
            };

            // TODO:调用API提交回复
            await courseApi.comment.addComment(replyData as CourseComment);
            console.log('回复提交成功');

            // 提交成功后重新获取评论列表
            await fetchComments(courseId.value);

            // 清空输入框并关闭回复区域
            replyContent.value = '';
            activeReplyId.value = null;
        } catch (error) {
            console.error('提交回复失败:', error);
        }
    };

    /**
     * 点赞评论
     * @param commentId 评论ID
     */
    const likeComment = async (commentId: number) => {
        try {
            // 判断当前用户是否已登录
            if (!currentUser.value) {
                console.error('请先登录');
                return;
            }

            // TODO:调用API进行点赞
            console.log('点赞功能待实现', commentId);

            // 更新评论列表
            await fetchComments(courseId.value);
        } catch (error) {
            console.error('点赞失败:', error);
        }
    };

    /**
     * 删除评论
     * @param commentId 评论ID
     */
    const deleteComment = async (commentId: number) => {
        // 保存当前要删除的评论ID
        currentDeleteId = commentId;
        // 设置标记，表明要删除的是评论而不是回复
        isReply = false;
        // 显示确认对话框
        deleteDialog.value.ShowModal();
    };

    /**
     * 删除回复
     * @param _commentId 父评论ID
     * @param replyId 回复ID
     */
    const deleteReply = async (_commentId: number, replyId: number) => {
        // 保存当前要删除的回复ID
        currentDeleteId = replyId;
        // 设置标记，表明要删除的是回复
        isReply = true;
        // 显示确认对话框
        deleteDialog.value.ShowModal();
    };

    /**
     * 取消删除操作
     */
    const cancelDelete = () => {
        // 关闭确认对话框
        deleteDialog.value.Close();
    };

    /**
     * 确认删除操作
     */
    const confirmDelete = async () => {
        if (currentDeleteId !== null) {
            try {
                // TODO:调用API删除评论或回复
                await courseApi.comment.deleteComment({
                    commentId: currentDeleteId
                } as CourseComment);
                console.log(`删除${isReply ? '回复' : '评论'}成功`);

                // 删除成功后重新获取评论列表
                await fetchComments(courseId.value);

                // 关闭确认对话框
                deleteDialog.value.Close();
            } catch (error) {
                console.error('删除失败:', error);
                deleteDialog.value.Close();
            }
        }
    };

    /**
     * 显示对回复的回复输入框
     * @param commentId 父评论ID
     * @param reply 被回复的回复对象
     */
    const showReplyToReply = (commentId: number, reply: CourseComment) => {
        // 清空回复内容
        replyContent.value = ``;
        // 设置当前活动的评论ID
        activeReplyId.value = commentId;
        // 保存被回复的回复对象
        replyToReply.value = reply;
    };

    const replyToUserName = (userName: string) => {
        return `<span class="replyToUserName">@ ${userName}</span>`;
    };

    /**
     * 提交对回复的回复
     * @param commentId 父评论ID
     */
    const submitReplyToReply = async (commentId: number) => {
        if (!replyContent.value.trim() || !replyToReply.value || !currentUser.value) return;

        let contentHtml = replyContent.value;
        try {
            if  (replyToReply) {
                // 解析HTML内容，并在第一个P标签中插入@用户名
                const parser = new DOMParser();
                const doc = parser.parseFromString(contentHtml, 'text/html');
                const pTag = doc.querySelector('p');
                if (pTag) {
                    pTag.innerHTML = `${replyToUserName(replyToReply.value?.userInfo?.nickName)} ${pTag.innerHTML}`;
                }
                contentHtml = doc.body.innerHTML;
            }
            // 构建回复对象
            const replyData: Partial<CourseComment> = {
                courseId: courseId.value,
                userId: currentUser.value.userId,
                parentId: commentId,  // 父评论ID
                content: contentHtml,
                score: 0,             // 初始点赞数为0
                // 可以在comment字段中添加额外信息，如被回复用户ID
                // 或者通过其他方式传递给后端
            };

            // TODO:调用API提交回复
            await courseApi.comment.addComment(replyData as CourseComment);
            console.log('回复提交成功');

            // 提交成功后重新获取评论列表
            await fetchComments(courseId.value);

            // 清空输入框并关闭回复区域
            replyContent.value = '';
            activeReplyId.value = null;
            replyToReply.value = null;
        } catch (error) {
            console.error('提交回复失败:', error);
        }
    };

    /**
     * 参数转换函数（确保字符串转换为数字）
     * @param value 要转换的值
     * @returns 转换后的数字，或undefined
     */
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };

    /**
     * 获取评论列表
     * @param courseId 课程ID
     */
    const fetchComments = async (courseId: number) => {
        try {
            const comments = await courseApi.comment.getList(courseId);
            console.log('获取到评论数据:', comments);
            commentList.value = comments || [];
        } catch (error) {
            console.error('获取评论失败:', error);
            commentList.value = [];
        }
    };

    /**
     * 监听路由参数的变化
     * 当路由参数变化时，重新获取评论列表
     */
    watch(
        () => ({
            courseIdParam: route.params.courseId
        }), async ({ courseIdParam }) => {
            courseId.value = parseSafeInt(courseIdParam) || 0;

            // 获取评论列表
            await fetchComments(courseId.value);
        },
        { immediate: true });
</script>

<style src="@/assets/icons/iconfont.css" scoped></style>

<style scoped>
.courseEvaluate {
    width: 100%;
    padding: 20px;
}

/* 评论输入区域样式 */
.comment-input-area {
    display: flex;
    gap: 12px;
    margin-bottom: 24px;
    padding: 16px;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
}

.user-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.comment-input-wrapper {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    min-height: 250px;
}

textarea {
    width: 100%;
    min-height: 80px;
    padding: 12px;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    resize: none;
    font-size: 14px;
    transition: all 0.3s;
}

textarea:focus {
    border-color: #41b9ff;
    outline: none;
}

.comment-tools {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 8px;
}

.right-tools {
    display: flex;
    align-items: center;
    gap: 12px;
}

.word-count {
    color: #999;
    font-size: 12px;
}

.send-btn {
    padding: 6px 16px;
    background: #41b9ff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.send-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 评论列表样式 */
.comment-list {
    margin-top: 24px;
}

.comment-item {
    padding: 16px;
    margin-bottom: 12px;
}

.comment-item:last-child {
    border-bottom: none;
}

.comment-item .user {
    display: flex;
    gap: 12px;
}

.comment-content {
    flex: 1;
}

.user-info {
    margin-bottom: 8px;
}

.username {
    font-weight: 500;
    color: #18191c;
    font-size: 14px;
}

.time {
    font-size: 12px;
    color: #9499a0;
    margin-left: 8px;
}

.text-content {
    font-size: 15px;
    line-height: 1.6;
    color: #4e5969;
    margin-bottom: 8px;
}
::v-deep .text-content .replyToUserName {
    color: rgba(135, 135, 135, 1);
    padding-right: 5px;
}

.comment-actions {
    display: flex;
    gap: 16px;
    margin-top: 8px;
}

.action-item {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #9499a0;
    cursor: pointer;
    transition: all 0.2s;
}

.action-item:hover {
    color: #41b9ff;
}

.action-item .iconfont {
    font-size: 16px;
}

/* 回复列表样式 */
.reply-list {
    margin-top: 12px;
    margin-left: 10px;
    padding: 8px;
}

.reply-item {
    display: flex;
    padding: 8px;
}

.reply-item:last-child {
    border-bottom: none;
}

.reply-content {
    flex: 1;
    margin-left: 12px;
}

.reply-content .comment-actions {
    display: flex;
    gap: 16px;
    margin-top: 8px;
}

.reply-content .action-item {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #9499a0;
    cursor: pointer;
    transition: all 0.2s;
}

.reply-content .action-item:hover {
    color: #41b9ff;
}

.reply-content .action-item .iconfont {
    font-size: 16px;
}

/* 回复输入框样式 */
.reply-input {
    margin-top: 12px;
    margin-left: 48px;
    display: flex;
    gap: 12px;
    padding: 12px;
    order: 2;
    /* 确保回复框显示在回复列表后面 */
}

.editor {
    margin-top: 10px;
    max-height: 300px;
    border-radius: 10px;
    border: 2px solid rgba(135, 135, 135, 0.5);
}

.editor:focus-within {
    border: 2px solid rgba(65, 185, 255, 1);
}

.reply-list {
    order: 1;
    /* 确保回复列表显示在回复框前面 */
}

.comment-content {
    display: flex;
    flex-direction: column;
}

.input-wrapper {
    flex: 1;
}

.input-wrapper textarea {
    width: 100%;
    height: 70px;
    padding: 8px 12px;
    border-radius: 4px;
    resize: none;
    font-size: 14px;
    line-height: 1.5;
    color: #4e5969;
}

.input-wrapper textarea:focus {
    border-color: #41b9ff;
    outline: none;
}

.input-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
}

.count {
    color: #9499a0;
    font-size: 12px;
}

.submit-btn {
    padding: 4px 12px;
    border-radius: 4px;
    background-color: #41b9ff;
    color: white;
    border: none;
    cursor: pointer;
    font-size: 13px;
}

.submit-btn:disabled {
    background-color: #e5e6eb;
    cursor: not-allowed;
}

.delete-btn {
    color: #ff4d4f;
    font-size: 12px;
    margin-left: 8px;
    cursor: pointer;
}

.delete-btn:hover {
    color: #ff7875;
}

.delete-confirm-content {
    padding: 20px;
    text-align: center;
}

.error-message {
    color: #ff4d4f;
    font-size: 16px;
}

.dialog-footer {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
    background: #fff;
    margin-top: 10px;
}

.dialog-footer:focus-within {
    background: #f5f5f5;
}

.cancel-btn,
.confirm-btn {
    flex: 1;
    height: 50px;
    border: none;
    background: none;
    cursor: pointer;
    font-size: 14px;
    color: #333;
    transition: all 0.3s;
    outline: none;
}

.cancel-btn:focus,
.confirm-btn:focus {
    outline: none;
    background: #f5f5f5;
}

.confirm-btn {
    color: #1890ff;
}

.divider {
    width: 1px;
    height: 24px;
    background-color: #cecece;
}

.cancel-btn:hover,
.confirm-btn:hover {
    background: #f5f5f5;
}

.cancel-btn:active,
.confirm-btn:active {
    outline: none;
}

.delete-confirm-content {
    padding: 20px;
    text-align: center;
}

.error-message {
    color: #ff4d4f;
    font-size: 16px;
}

/* 覆盖 MessageDialog 组件的样式 */
:deep(.messageDialog) {
    border-radius: 0 !important;
    min-height: 180px !important;
}

.action-item .iconfont.active {
    color: #41b9ff;
}

.action-item:has(.icon-likesprogramcai.active) {
    color: #ff4d4f;
}

.action-item:has(.icon-likesprogramcai.active) .icon-likesprogramcai {
    color: #ff4d4f;
}

.reply-to {
    color: #9499a0;
    font-size: 12px;
    margin-left: 8px;
}

.at-user {
    color: #41b9ff;
    font-weight: 500;
    margin-right: 4px;
}

.text-content .at-user {
    margin-right: 4px;
    cursor: pointer;
}

.text-content .at-user:hover {
    text-decoration: underline;
}
</style>